package org.example.fboot.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.ReactiveAuthenticationManager;
import org.springframework.security.authentication.UserDetailsRepositoryReactiveAuthenticationManager;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.method.configuration.EnableReactiveMethodSecurity;
import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity;
import org.springframework.security.config.web.server.ServerHttpSecurity;
import org.springframework.security.core.userdetails.ReactiveUserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.server.SecurityWebFilterChain;
import org.springframework.security.web.server.context.ServerSecurityContextRepository;

@Slf4j
@EnableWebFluxSecurity
@Configuration
@EnableReactiveMethodSecurity(useAuthorizationManager = true)
public class WebFluxSecurityConfigurer {
    @Bean
    public ReactiveAuthenticationManager authenticationManager(ReactiveUserDetailsService userService, PasswordEncoder passwordEncoder) {
        log.info("加载security 用户配置....");
        UserDetailsRepositoryReactiveAuthenticationManager manager = new UserDetailsRepositoryReactiveAuthenticationManager(userService);
        manager.setPasswordEncoder(passwordEncoder);
        return manager;
    }

    /**
     * security声明 TODO 可以注入dao来配置权限等
     *
     * @param http
     * @return
     */
    @Bean
    public SecurityWebFilterChain securityFilterChain(ServerHttpSecurity http,ServerSecurityContextRepository securityContextRepository) {
        log.info("加载security securityFilterChain....");
        http.cors(ServerHttpSecurity.CorsSpec::disable)
                .csrf(ServerHttpSecurity.CsrfSpec::disable)
                .httpBasic(Customizer.withDefaults())
                .formLogin(Customizer.withDefaults())
                .securityContextRepository(securityContextRepository)
        ;
        return http.build();
    }

    /**
     * 密码校验，可以自定义密码加解密
     *
     * @return
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder(4);
    }
}
